//
//  DVImagePickerController.m
//  ImagePicker
//
//  Created by csh on 16/4/13.
//  Copyright © 2016年 com.read. All rights reserved.
//
#import "DVChoosePhotoAlbumViewController.h"
#import "NSMutableArray+ImagePicker.h"
#import "DVImagePickerNavigationController.h"
#import "DVPhotoCell.h"
#import "DVImagePickerController.h"


@interface DVImagePickerController ()<UICollectionViewDataSource,UICollectionViewDelegate,DVPhotoCellDelegate,DVChoosePhotoAlbumViewControllerDelegate>
@property (nonatomic,strong)NSArray *photoArray;
@property(nonatomic,strong)DVChoosePhotoAlbumViewController *chooseVC;
@property(nonatomic,weak)UICollectionView *collectionView;
@property(nonatomic,weak)UIButton *titleBtn;
@end

@implementation DVImagePickerController
- (NSMutableArray *)selectPhotoArray
{
    if(_selectPhotoArray==nil)
    {
        _selectPhotoArray = [[NSMutableArray alloc]init];
    }
    return _selectPhotoArray;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initNavigationBar];

    
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    [button setTitle:@"相机胶卷" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(choosePhoneAlbum:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = button;
    self.titleBtn=button;
    [self configSubTableView];
    [[DVImagePickerManager manager] getPhotosWithAlbum:self.model.result completion:^(NSArray<DVAssetModel *> *photoArray) {
        self.photoArray = photoArray;
        [self configCollectionView];
    }];
}

- (void)initNavigationBar
{
    LeftButton *button = [[LeftButton alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
    [button addTarget:self action:@selector(popController) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:17];
    button.titleLabel.textAlignment = NSTextAlignmentLeft;
    [button setTitle:NSLocalizedString(@"back", nil) forState:UIControlStateNormal];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"yes", nil) style:UIBarButtonItemStylePlain target:self action:@selector(okButtonClick)];
    [self.navigationItem.rightBarButtonItem setTintColor:[UIColor whiteColor]];
}

#pragma - mark  configCollectionView
- (void)configCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width-10)/3, ([UIScreen mainScreen].bounds.size.width-10)/3);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 5;
    flowLayout.minimumInteritemSpacing =5;
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [collectionView registerClass:[DVPhotoCell class] forCellWithReuseIdentifier:@"PhotoCellectionCell"];
    [self.view addSubview:collectionView];
    NSMutableArray *collectionViewConstraint = [[NSMutableArray alloc]init];
    [collectionViewConstraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[collectionView]-(0)-|" options:0 metrics:nil views:@{@"collectionView":collectionView}]];
    [collectionViewConstraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[collectionView]-(0)-|" options:0 metrics:nil views:@{@"collectionView":collectionView}]];
    [self.view addConstraints:collectionViewConstraint];
    self.collectionView=collectionView;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.photoArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DVPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCellectionCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.model = self.photoArray[indexPath.item];
    [cell compareWithAsset:self.selectPhotoArray];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DVPhotoCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell selectButtonClick:cell.selectButton];
}

#pragma - mark DelagateMethod
- (void)didSelectImageWithModel:(DVAssetModel *)model select:(BOOL)select
{
    if(select)
    {
        [self.selectPhotoArray addObject:model];
    }else
    {
        [self.selectPhotoArray deleteObject:model];
    }
}



#pragma - mark popController
- (void)popController
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)okButtonClick
{
    if(self.selectPhotoArray.count>9)
    {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"image must be less 9" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
        [alertView show];
    }else
    {
        __block int j = 0;
        NSMutableArray *imageArray = [[NSMutableArray alloc]init];
        for(int i=0;i<self.selectPhotoArray.count;i++)
        {
            
            __block DVAssetModel *model = self.selectPhotoArray[i];
            [[DVImagePickerManager manager] getPhotoWithAsset:model.asset completion:^(UIImage *image, NSDictionary *info, BOOL isDegraded) {
                [imageArray addObject:image];
                
                j++;
                if(j==self.selectPhotoArray.count)
                {
                    DVImagePickerNavigationController *navigation = (DVImagePickerNavigationController *)self.navigationController;
                    if([navigation.responder respondsToSelector:@selector(didChooseImages:assets:sourceVC:)])
                    {
                        [navigation.responder didChooseImages:imageArray assets:self.selectPhotoArray sourceVC:navigation];
//                        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                    }
                }
            }];
        }
    }
    
}
-(void)configSubTableView
{

//    [self.view bringSubviewToFront:self.chooseVC.view];

}
-(DVChoosePhotoAlbumViewController *)chooseVC{
    if (!_chooseVC) {
        _chooseVC = [[DVChoosePhotoAlbumViewController  alloc]init];
        _chooseVC.seletedDelegate=self;
        _chooseVC.sourceVC=self;
        [self.view addSubview:_chooseVC.view];
        [self addChildViewController:_chooseVC];

    }
    return _chooseVC;
}
#pragma - mark choose PhoneAlbum
- (void)choosePhoneAlbum:(UIButton *)btn
{
    if (self.isClick==YES) {
        self.isClick=NO;
        [self.chooseVC hidden];
      
    }else{
        self.isClick=YES;
        [self.chooseVC show];
       
    }



}
#pragma mark choosePhotoVC
-(void)choosePhotoAlbumViewController:(DVChoosePhotoAlbumViewController *)vc didSelectedModelArray:(NSMutableArray *)array title:(NSString *)title
{
    self.photoArray=array;
    [vc hidden];
    [self.titleBtn setTitle:title forState:UIControlStateNormal];
    [self.collectionView reloadData];
}
@end
